/*
 * @Author: LBH 1336709799@qq.com
 * @Date: 2024-12-09 09:13:20
 * @LastEditors: LBH 1336709799@qq.com
 * @LastEditTime: 2024-12-09 21:30:21
 * @FilePath: \hm-admin\src\utils\reuqest.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios, { type Method } from 'axios'
import { getLocalToken } from './auth'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})

service.interceptors.request.use(
  config => {
    const token = getLocalToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    ElMessage.error(error.response.data.message)
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    ElMessage.error(error.response.data.msg);
    if(error.response.status===401){
      const router = useRouter()
      router.push('/login')
      const store = useUserStore()
      store.clearUserInfo()
    }
    return Promise.reject(error)
  },
)
// 定义返回类型
type Data<T> = {
  code: number
  message: string
  data: T
}
// 请求工具函数
const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
  return service.request<T,Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}

export { request }
export default service
